package com.zg.utils;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * 从spring中取出相应的bean，适用于没有被spring管理的普通类，
 * spring管理的对象是单例的，如果我们使用new来创建那么里面spring管理的对象在使用的时候就会报空指针异常
 */
@Component
public class SpringContextUtil implements ApplicationContextAware {
    private static ApplicationContext applicationContext = null;


    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        if (SpringContextUtil.applicationContext==null){
            SpringContextUtil.applicationContext = applicationContext;
        }
    }


    public static ApplicationContext getApplicationContext(){
        return applicationContext;
    }

    @SuppressWarnings("unchecked")
    public static <T> T getBean(String name){
        return (T) applicationContext.getBean(name);
    }

    public static <T> T getBean(Class<T> tClass){
        return (T) applicationContext.getBean(tClass);
    }
}
